package parser;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.w3c.dom.Document;

import util.Candle;
import util.Util;

public class I3ttpParser { 
	
	private LinkedHashMap<String, Rating> avgTargetPrices;
	
	public LinkedHashMap<String, Rating> getTargetPrices() {
		return avgTargetPrices;
	}
	
	public Rating getRating(String stockName) {
		if (avgTargetPrices.get(stockName) == null) return null;
		else return avgTargetPrices.get(stockName);
	}
	
	public I3ttpParser(String filename) {
		try {
	        String content = getText(filename);
	
	        String regex = "target=\"_top\">(.*?)</a>.*?(\\d+.\\d+).*?(\\d+.\\d+).*?rating(\\d+).*?</tr>";
	        Pattern p = Pattern.compile(regex); 
	        Matcher m = p.matcher(content);
	
	        avgTargetPrices = new LinkedHashMap<String, Rating>();
	        while (m.find()) {
	        	String content1 = m.group(0);
            	String matchedStockName = I3.matchStockname(m.group(1));
            	float targetPrice = Float.parseFloat(m.group(3));
            	int rating = Integer.parseInt(m.group(4));
            	avgTargetPrices.put(matchedStockName, new Rating(targetPrice, rating));
	        }
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
    private String getText(String filename) throws Exception { 
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename),"UTF-8"));
			String line;
	        StringBuilder response = new StringBuilder(); 
			while ((line = br.readLine()) != null) {
	            response.append(line); 
			}
	        return response.toString(); 
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
    } 
 
    public static void main(String[] args) throws Exception { 
    	I3ttpParser i3ttpParser = new I3ttpParser(args[0]);

		Iterator<String> iter = i3ttpParser.avgTargetPrices.keySet().iterator();
		while (iter.hasNext()) {
			String stockName = iter.next();
        	Rating rating = i3ttpParser.avgTargetPrices.get(stockName);
			String paddedStockName = String.format("%1$-30s", stockName);
       		System.out.println(paddedStockName + "\t" + rating.getAvgTargetPrice() + "\t" + rating.getRating());
		}
    } 
} 
